package org.feng.support;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.feng.entity.SysScheduler;
import org.feng.mapper.SysSchedulerMapper;
import org.quartz.*;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 定时任务支持
 *
 * @author : FengShuai
 * @since : 2024/6/27 9:24
 */
@Component
@Slf4j
public class SchedulerSupport {
    @Resource
    private Scheduler scheduler;
    @Resource
    private SysSchedulerMapper sysSchedulerMapper;

    /**
     * 初始化定时任务
     */
    @PostConstruct
    public void init() throws SchedulerException {
        log.info("初始化定时任务...................");
        List<SysScheduler> sysSchedulers = sysSchedulerMapper.selectList(Wrappers.emptyWrapper());
        for (SysScheduler sysScheduler : sysSchedulers) {
            invoke(sysScheduler);
            log.info("初始化定时任务:{},名称：{}", sysScheduler.getId(), sysScheduler.getName());
        }
        log.info("初始化定时任务完成");
    }

    /**
     * 删除定时任务
     */
    public void delete(String id) {
        try {
            scheduler.deleteJob(getJobKey(id));
        } catch (SchedulerException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 执行定时任务
     */
    public void invoke(SysScheduler sysScheduler) throws SchedulerException {
        if (sysScheduler.getStatus()) {
            //判断是否存在
            if (scheduler.checkExists(getJobKey(sysScheduler.getId()))) {
                //先删除后创建
                scheduler.deleteJob(getJobKey(sysScheduler.getId()));
            }
            //构建执行器
            Class<? extends Job> job = sysScheduler.getConcurrent() ? JobExecute.class : JobConcurrentExecute.class;
            //构建任务
            JobDetail jobDetail = JobBuilder.newJob(job).withIdentity(sysScheduler.getId()).build();
            //构建cron
            CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(sysScheduler.getCron())
                    //重启服务后不执行任务
                    .withMisfireHandlingInstructionDoNothing();
            //构建触发器
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(sysScheduler.getId()).withSchedule(cronScheduleBuilder).build();
            //添加参数
            jobDetail.getJobDataMap().put("data", sysScheduler);
            //执行任务
            scheduler.scheduleJob(jobDetail, trigger);
        } else {
            scheduler.deleteJob(getJobKey(sysScheduler.getId()));
        }
    }

    /**
     * 获取定时任务
     */
    private JobKey getJobKey(String id) {
        return JobKey.jobKey(id);
    }

}
